package com.example.controller;

import com.example.entity.CurrentUser;
import com.example.entity.LoginUser;
import com.example.entity.Result;
import com.example.entity.User;
import com.example.service.AuthService;
import com.example.service.UserService;
import com.example.utils.DigestUtil;
import com.example.utils.TokenUtils;
import com.example.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:tjf
 * @Description:
 */
@RestController
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AuthService authService;
    /**
     * 登录的url接口 /login
     * @return
     */
    @RequestMapping("/login")
    public Result login(@RequestBody LoginUser loginUser){
        // 校验验证码是否正确
        if (!stringRedisTemplate.hasKey(loginUser.getVerificationCode())){// 验证码不存在
            return Result.err(Result.CODE_ERR_BUSINESS, "验证码不正确！");
        }

        // 查询用户账号
        User user = userService.findUserByCode(loginUser.getUserCode());
        if (user != null){// 用户账号存在
            if (WarehouseConstants.USER_STATE_PASS.equals(user.getUserState())){// 用户已通过审核
                // 密码验证 需要先用MD5加密，再比较
                String loginPwd = DigestUtil.hmacSign(loginUser.getUserPwd());
                if (loginPwd.equals(user.getUserPwd())){// 密码正确
                    // 令牌操作
                    CurrentUser currentUser = new CurrentUser(user.getUserId(),
                            user.getUserCode(), user.getUserName());
                    // 生成令牌
                    String token = tokenUtils.loginSign(currentUser, loginPwd);

                    return Result.ok("登录成功！", token);
                }else{// 密码不正确
                    return Result.err(Result.CODE_ERR_BUSINESS, "用户密码错误！");
                }
            }else{// 用户未通过审核
                return Result.err(Result.CODE_ERR_BUSINESS, "用户未审核！");
            }
        }else{// 用户账号不存在
            return Result.err(Result.CODE_ERR_BUSINESS, "用户账号不存在！");
        }
    }

    /**
     * 获取当前用户信息的接口url/curr-user
     * @return
     */
    @RequestMapping("/curr-user")
    public Result getCurrentUser(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        // 根据前端归还的token获取当前用户信息
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        // 响应前端
        return Result.ok(currentUser);
    }

}
